package com.atguigu.tingshu.album.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


/**
 * @author sun
 */
@Service
public class VodServiceImpl implements VodService {

    private static final Logger log = LoggerFactory.getLogger(VodServiceImpl.class);
    @Resource
    private VodConstantProperties vodConstantProperties;

    /**
     * 上传声音
     *
     * @param file 声音文件
     * @return mediaFileId 声音文件id  和 mediaUrl 声音文件url
     */
    @SneakyThrows
    @Override
    public Map<String, Object> uploadTrack(MultipartFile file) {
        // 上传到临时目录
        String tempPath = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), file);
        // 客户端创建
        VodUploadClient vodUploadClient = new VodUploadClient(
                vodConstantProperties.getSecretId(),
                vodConstantProperties.getSecretKey());
        // 创建请求
        VodUploadRequest request = new VodUploadRequest();
        request.setMediaFilePath(tempPath);
        // 上传
        VodUploadResponse uploadResponse = vodUploadClient.upload(vodConstantProperties.getRegion(), request);
        // 返回
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("mediaFileId", uploadResponse.getFileId());
        hashMap.put("mediaUrl", uploadResponse.getMediaUrl());

        return hashMap;
    }

    /**
     * 根据声音文件的mediaFileId在腾讯云上
     * 获取媒体详细信息
     * <p>
     * <a href="https://cloud.tencent.com/document/product/266/31763">腾讯云api文档地址</a>
     * </p>
     *
     * @param mediaFileId 声音文件id
     * @return 声音文件的相应媒体信息
     */
    @SneakyThrows
    @Override
    public TrackMediaInfoVo getTrackMediaInfo(String mediaFileId) {

        /*
         实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
         代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，
         请参见：https://cloud.tencent.com/document/product/1278/85305
         密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
        */
        Credential cred = new Credential(vodConstantProperties.getSecretId(),
                vodConstantProperties.getSecretKey());
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("vod.tencentcloudapi.com");
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        VodClient client = new VodClient(cred,vodConstantProperties.getRegion(), clientProfile);


        // 实例化一个请求对象,每个接口都会对应一个request对象
        DescribeMediaInfosRequest req = new DescribeMediaInfosRequest();
        // 媒体文件id
        req.setFileIds(new String[]{mediaFileId});
        // 应用id
        req.setSubAppId(vodConstantProperties.getAppId().longValue());
        //指定媒体文件需要返回的信息
        req.setFilters(new String[]{"basicInfo", "metaData"});


        // 返回的resp是一个DescribeMediaInfosResponse的实例，与请求对象对应
        DescribeMediaInfosResponse resp = client.DescribeMediaInfos(req);

        log.info("请求返回了声音文件的相应媒体信息：{}", JSON.toJSONString(resp));

        MediaInfo[] mediaInfoSet = resp.getMediaInfoSet();
        if (mediaInfoSet != null && mediaInfoSet.length > 0) {
            MediaInfo mediaInfo = mediaInfoSet[0];
            return TrackMediaInfoVo.builder()
                    .type(mediaInfo.getBasicInfo().getType())
                    .mediaUrl(mediaInfo.getBasicInfo().getMediaUrl())
                    .duration(mediaInfo.getMetaData().getDuration())
                    .size(mediaInfo.getMetaData().getSize())
                    .build();
        }{
            log.error("声音文件不存在");
            throw new GuiguException(404,"声音文件不存在");
        }
    }

    /**
     * 根据媒体id 删除媒体文件
     *
     * @param mediaFileId 媒体id
     */
    @SneakyThrows
    @Override
    public void removeMediaFile(String mediaFileId) {
        Credential credential = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
        VodClient vodClient = new VodClient(credential, vodConstantProperties.getRegion());
        DeleteMediaRequest deleteMediaRequest = new DeleteMediaRequest();
        deleteMediaRequest.setFileId(mediaFileId);
        DeleteMediaResponse deleteMediaResponse = vodClient.DeleteMedia(deleteMediaRequest);
        log.info("删除声音文件成功：{}", JSON.toJSONString(deleteMediaResponse));

    }
}
